package com.iweb.day11;

import java.sql.*;
import java.util.Scanner;

/**
 * @author WuYongheng
 * @date 2021/11/28
 * @description 进行登录验证，学号+密码
 */
public class Test5 {
    public static void main(String[] args) {
        Connection conn = null;
        // 换成PreparedStatement
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Scanner scanner = new Scanner(System.in);
        // 数据库连接信息
        String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
        String username = "hr";
        String password = "123456";
        try {
            // 加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            // 连接对象
            conn = DriverManager.getConnection(url, username, password);
            if (conn != null) {
                System.out.println("连接成功");
            }
            System.out.println("学生数据库登录界面：");
            System.out.print("请输入学号：");
            int no = Integer.parseInt(scanner.nextLine());
            System.out.print("请输入密码：");
            String pwd = scanner.nextLine();

//            String sql = "select count(*) from student " +
//                    "where studentno = " + no +
//                    " and loginpwd='" + pwd + "' ";
            // sql中的至都换成?,进行占位
            String sql = "select count(*) from student where studentno =? and loginpwd=?";
            // 创建statement对象
            statement = conn.prepareStatement(sql);
            // 为sql中的?赋值
            statement.setInt(1, no);
            statement.setString(2, pwd);

            resultSet = statement.executeQuery();

            int result = -1;
            if (resultSet.next()) {
                result = resultSet.getInt(1);
            }
            // 判断结果
            if (result > 0) {
                System.out.println("登录成功");
            } else {
                System.out.println("登录失败,学号或密码有误!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
